package com.bw.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<uiintent:UIIntent>:ViewModel() {
    private val _uiintent:Channel<UIIntent> = Channel<UIIntent> {Channel.UNLIMITED}

    private val _state:MutableStateFlow<UIState> = MutableStateFlow<UIState>(UIState.Onloading)

    val state:StateFlow<UIState>
        get()=_state

    init {
        viewModelScope.launch {
            _uiintent.receiveAsFlow().collect{
                handleintent(it)
            }
        }
    }

    abstract fun handleintent(it:UIIntent)

    fun sendintent(uiIntent: UIIntent){
        viewModelScope.launch {
            _uiintent.send(uiIntent)
        }
    }

    fun httprequest(request:Flow<Res<Any>>,type: StateType){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("wxc", "网络请求错误${it.message}")
                    ToastUtils.showLong("网络请求错误${it.message}")
                }.collect{
                    if(it.code == 200){
                        _state.value = UIState.OnSuccess(it.data,type)
                    }else{
                        _state.value =UIState.OnError(it.message)
                    }
                }
        }
    }
}